package com.mjk.common.tools.gson.adapter.impl;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.mjk.common.util.TimeUtils;

import java.io.IOException;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * localdatetime 序列化转换器
 */
public class LocalTimeAdapterImpl extends TypeAdapter<LocalTime> {
    @Override
    public void write(JsonWriter jsonWriter, LocalTime localDateTime) throws IOException {
        if(null == localDateTime){
            jsonWriter.value("");
        }else {
            jsonWriter.value(localDateTime.format(DateTimeFormatter.ofPattern(TimeUtils.DATE_FORMAT_TIME)));
        }
    }

    @Override
    public LocalTime read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            return null;
        }
        return LocalTime.ofInstant(TimeUtils.parse(in.nextString()).toInstant(), ZoneId.systemDefault());
    }
}
